﻿using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace lucene_test
{
    public partial class Form2 : Form
    {
        private int _indexCount = 0;
        private string[] _coulumnNames =
        {
            "ORGID","ORGCODE","ORGNAME","SHORTNAME",/*"GLOBALPCCODE",
            "PARENTORGID","TELEPHONE","FAX","URL","CORPORATIONTYPE",
            "REGISTERFUND","WORKINGSCOPE","STATUS","REGIONCODE","CITYCODE",
            "SALESCHANNELID","TARGETTYPE","EMAIL","ADDRESS","ZIPCODE",
            "HOSPITALLEVEL","BUSINESSLICENSE","BUSINESSCERTIFICATE","CONTACTNAME","COUNTYCODE",*/
            "REGIONNAME","CITYNAME","COUNTYNAME"/*,"REGISTERNO","CHAINTYPE",
            "GRADENAME","PARITYFLAG","MEDICAREFLAG","OUTPATIENTSQTY","BEDSQTY",
            "DATASOURCE","CHANNEL","GLOBALPCNAME","LATESTTIME","POPCHANNEL"*/
        };

        public Form2()
        {
            InitializeComponent();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    txtFileName.Text = dlg.FileName;
                }
            }
        }

        /// <summary>
        /// 创建索引
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bkwCreateIndex_DoWork(object sender, DoWorkEventArgs e)
        {
            string fileName = txtFileName.Text;
            string connectString = string.Format(
                "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}",
                fileName);
            int rowCount = 0;
            int pageSize = 1000;
            int pages = 0;
            int pageIndex = 0;
            OleDbConnection conn = null;
            try
            {
                conn = new OleDbConnection(connectString); //Jet OLEDB:Database Password=

                OleDbCommand cmd = conn.CreateCommand();
                cmd.CommandText = "select * from BIPALL_CDMS_ORGANIZATION";
                conn.Open();
                OleDbDataReader dbReader = cmd.ExecuteReader();
                if (dbReader.HasRows)
                {
                    using (var writer = GetIndexWriter())
                    {
                        while (dbReader.Read())
                        {
                            string orgId = "";
                            orgId = dbReader["ORGID"].ToString();
                            writer.DeleteDocuments(new Term("ORGID", orgId));
                            Document doc = new Document();
                            for (int i = 0; i < _coulumnNames.Length; i++)
                            {
                                Field field = new Field(
                                    _coulumnNames[i],
                                    dbReader[_coulumnNames[i]].ToString(),
                                    Field.Store.YES,
                                    i == 0 ? Field.Index.NOT_ANALYZED : Field.Index.ANALYZED);
                                    //Field.Index.NOT_ANALYZED);
                                doc.Add(field);
                            }

                            writer.AddDocument(doc);

                            ++rowCount;
                            bkwCreateIndex.ReportProgress(rowCount, orgId);
                            if (rowCount > 99999)
                            {
                                break;
                            }
                        }
                        writer.Optimize();
                        writer.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                bkwCreateIndex.ReportProgress(rowCount, ex.Message);
            }
            finally
            {
                if (conn != null && conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bkwCreateIndex_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblRowCount.Text = e.ProgressPercentage.ToString();
            lblRowCount.Update();

            StringBuilder sb = new StringBuilder(txtLog.Text);
            sb.Append("\n" + e.UserState.ToString());
            txtLog.Text = sb.ToString();
        }

        /// <summary>
        /// 创建完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bkwCreateIndex_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("创建完成");
            btnExcute.Enabled = true;
            btnStop.Enabled = false;
        }

        private void btnExcute_Click(object sender, EventArgs e)
        {
            btnExcute.Enabled = false;
            btnStop.Enabled = true;
            bkwCreateIndex.RunWorkerAsync();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            btnExcute.Enabled = true;
            btnStop.Enabled = false;
            bkwCreateIndex.CancelAsync();
        }

        private IndexWriter GetIndexWriter()
        {
            var dir = FSDirectory.Open(@"D:\Index");
            //Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
            Analyzer analyzer = new PanGuAnalyzer();
            bool isCreate = !IndexReader.IndexExists(dir);
            var writer = new IndexWriter(dir, analyzer, isCreate, IndexWriter.MaxFieldLength.UNLIMITED);
            return writer;
        }
    }
}
